{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Orchestrator-Workers Workflow\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Have you ever needed multiple perspectives on the same task, but couldn't predict in advance which perspectives would be most valuable? The orchestrator-workers pattern solves this by having a central LLM analyze each unique task and dynamically determine the best subtasks to delegate to specialized worker LLMs.\n",
    "\n",
    "Traditional approaches either require manual prompting multiple times or use hardcoded parallelization that generates the same variations regardless of context.\n",
    "\n",
    "With this approach, an orchestrator LLM analyzes the task, determines which variations would be most valuable for this specific case, then delegates to worker LLMs that generate each variation.\n",
    "\n",
    "### What You'll Build\n",
    "\n",
    "A system that takes a product description request and:\n",
    "\n",
    "1. Analyzes what types of marketing copy would be valuable\n",
    "2. Dynamically generates specialized task descriptions for workers\n",
    "3. Produces multiple content variations optimized for different audiences\n",
    "4. Returns coordinated results from all workers\n",
    "\n",
    "### Prerequisites\n",
    "\n",
    "- Python 3.9 or higher\n",
    "- Anthropic API key set as environment variable: `export ANTHROPIC_API_KEY='your-key'`\n",
    "- Basic understanding of prompt engineering\n",
    "- Familiarity with Python classes and type hints\n",
    "\n",
    "\n",
    "### When to use this workflow\n",
    "\n",
    "This workflow is well-suited for complex tasks where you can't predict the subtasks needed in advance. The key difference from simple parallelization is its flexibility—subtasks aren't pre-defined, but determined by the orchestrator based on the specific input.\n",
    "\n",
    "**Use this pattern when:**\n",
    "\n",
    "- Tasks require multiple distinct approaches or perspectives\n",
    "- The optimal subtasks depend on the specific input\n",
    "- You need to compare different strategies or styles\n",
    "\n",
    "**Don't use this pattern when:**\n",
    "\n",
    "- You have simple, single-output tasks (unnecessary complexity)\n",
    "- Latency is critical (multiple LLM calls add overhead)\n",
    "- Subtasks are predictable and can be pre-defined (use simpler parallelization)\n",
    "\n",
    "## How It Works\n",
    "\n",
    "The orchestrator-workers pattern operates in two phases:\n",
    "\n",
    "1. **Analysis & Planning Phase**: The orchestrator LLM receives the task and context, analyzes what approaches would be valuable, and generates structured subtask descriptions in XML format.\n",
    "\n",
    "2. **Execution Phase**: Each worker LLM receives:\n",
    "   - The original task for context\n",
    "   - Its specific subtask type and description\n",
    "   - Any additional context provided\n",
    "\n",
    "The orchestrator decides *at runtime* what subtasks to create, making this more adaptive than pre-defined parallel workflows."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "### Installation\n",
    "```bash\n",
    "pip install anthropic\n",
    "```\n",
    "\n",
    "### Helper Functions\n",
    "This example uses helper functions from `util.py` for making LLM calls and parsing XML responses:\n",
    "\n",
    "- `llm_call(prompt, system_prompt=\"\", model=\"claude-sonnet-4-5\")`: Sends a prompt to Claude and returns the text response\n",
    "- `extract_xml(text, tag)`: Extracts content from XML tags using regex\n",
    "\n",
    "These utilities handle API authentication (reading `ANTHROPIC_API_KEY` from environment) and provide a simple interface for the orchestrator-workers pattern. You can view the complete implementation in [util.py](util.py).\n",
    "\n",
    "## Implementation\n",
    "\n",
    "The `FlexibleOrchestrator` class coordinates the two-phase workflow:\n",
    "\n",
    "**Key design decisions:**\n",
    "- Prompts are templates that accept runtime variables (`task`, `context`) for flexibility\n",
    "- XML is used for structured output parsing (reliable and language-model-friendly format)\n",
    "- Workers receive both the original task AND their specific instructions for better context\n",
    "- Error handling validates that workers return non-empty responses\n",
    "\n",
    "The implementation includes:\n",
    "- `parse_tasks()`: Parses the orchestrator's XML output into structured task dictionaries\n",
    "- `FlexibleOrchestrator.process()`: Main coordination logic that calls orchestrator, then workers\n",
    "- Response validation to catch and handle empty worker outputs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from util import extract_xml, llm_call\n",
    "\n",
    "# Model configuration\n",
    "MODEL = \"claude-sonnet-4-5\"  # Fast, capable model for both orchestrator and workers\n",
    "\n",
    "\n",
    "def parse_tasks(tasks_xml: str) -> list[dict]:\n",
    "    \"\"\"Parse XML tasks into a list of task dictionaries.\"\"\"\n",
    "    tasks = []\n",
    "    current_task = {}\n",
    "\n",
    "    for line in tasks_xml.split(\"\\n\"):\n",
    "        line = line.strip()\n",
    "        if not line:\n",
    "            continue\n",
    "\n",
    "        if line.startswith(\"<task>\"):\n",
    "            current_task = {}\n",
    "        elif line.startswith(\"<type>\"):\n",
    "            current_task[\"type\"] = line[6:-7].strip()\n",
    "        elif line.startswith(\"<description>\"):\n",
    "            current_task[\"description\"] = line[12:-13].strip()\n",
    "        elif line.startswith(\"</task>\"):\n",
    "            if \"description\" in current_task:\n",
    "                if \"type\" not in current_task:\n",
    "                    current_task[\"type\"] = \"default\"\n",
    "                tasks.append(current_task)\n",
    "\n",
    "    return tasks\n",
    "\n",
    "\n",
    "class FlexibleOrchestrator:\n",
    "    \"\"\"Break down tasks and run them in parallel using worker LLMs.\"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        orchestrator_prompt: str,\n",
    "        worker_prompt: str,\n",
    "        model: str = MODEL,\n",
    "    ):\n",
    "        \"\"\"Initialize with prompt templates and model selection.\"\"\"\n",
    "        self.orchestrator_prompt = orchestrator_prompt\n",
    "        self.worker_prompt = worker_prompt\n",
    "        self.model = model\n",
    "\n",
    "    def _format_prompt(self, template: str, **kwargs) -> str:\n",
    "        \"\"\"Format a prompt template with variables.\"\"\"\n",
    "        try:\n",
    "            return template.format(**kwargs)\n",
    "        except KeyError as e:\n",
    "            raise ValueError(f\"Missing required prompt variable: {e}\") from e\n",
    "\n",
    "    def process(self, task: str, context: dict | None = None) -> dict:\n",
    "        \"\"\"Process task by breaking it down and running subtasks in parallel.\"\"\"\n",
    "        context = context or {}\n",
    "\n",
    "        # Step 1: Get orchestrator response\n",
    "        orchestrator_input = self._format_prompt(self.orchestrator_prompt, task=task, **context)\n",
    "        orchestrator_response = llm_call(orchestrator_input, model=self.model)\n",
    "\n",
    "        # Parse orchestrator response\n",
    "        analysis = extract_xml(orchestrator_response, \"analysis\")\n",
    "        tasks_xml = extract_xml(orchestrator_response, \"tasks\")\n",
    "        tasks = parse_tasks(tasks_xml)\n",
    "\n",
    "        print(\"\\n\" + \"=\" * 80)\n",
    "        print(\"ORCHESTRATOR ANALYSIS\")\n",
    "        print(\"=\" * 80)\n",
    "        print(f\"\\n{analysis}\\n\")\n",
    "\n",
    "        print(\"\\n\" + \"=\" * 80)\n",
    "        print(f\"IDENTIFIED {len(tasks)} APPROACHES\")\n",
    "        print(\"=\" * 80)\n",
    "        for i, task_info in enumerate(tasks, 1):\n",
    "            print(f\"\\n{i}. {task_info['type'].upper()}\")\n",
    "            print(f\"   {task_info['description']}\")\n",
    "\n",
    "        print(\"\\n\" + \"=\" * 80)\n",
    "        print(\"GENERATING CONTENT\")\n",
    "        print(\"=\" * 80 + \"\\n\")\n",
    "\n",
    "        # Step 2: Process each task\n",
    "        worker_results = []\n",
    "        for i, task_info in enumerate(tasks, 1):\n",
    "            print(f\"[{i}/{len(tasks)}] Processing: {task_info['type']}...\")\n",
    "\n",
    "            worker_input = self._format_prompt(\n",
    "                self.worker_prompt,\n",
    "                original_task=task,\n",
    "                task_type=task_info[\"type\"],\n",
    "                task_description=task_info[\"description\"],\n",
    "                **context,\n",
    "            )\n",
    "\n",
    "            worker_response = llm_call(worker_input, model=self.model)\n",
    "            worker_content = extract_xml(worker_response, \"response\")\n",
    "\n",
    "            # Validate worker response - handle empty outputs\n",
    "            if not worker_content or not worker_content.strip():\n",
    "                print(f\"⚠️  Warning: Worker '{task_info['type']}' returned no content\")\n",
    "                worker_content = f\"[Error: Worker '{task_info['type']}' failed to generate content]\"\n",
    "\n",
    "            worker_results.append(\n",
    "                {\n",
    "                    \"type\": task_info[\"type\"],\n",
    "                    \"description\": task_info[\"description\"],\n",
    "                    \"result\": worker_content,\n",
    "                }\n",
    "            )\n",
    "\n",
    "        # Display results\n",
    "        print(\"\\n\" + \"=\" * 80)\n",
    "        print(\"RESULTS\")\n",
    "        print(\"=\" * 80)\n",
    "        for i, result in enumerate(worker_results, 1):\n",
    "            print(f\"\\n{'-' * 80}\")\n",
    "            print(f\"Approach {i}: {result['type'].upper()}\")\n",
    "            print(f\"{'-' * 80}\")\n",
    "            print(f\"\\n{result['result']}\\n\")\n",
    "\n",
    "        return {\n",
    "            \"analysis\": analysis,\n",
    "            \"worker_results\": worker_results,\n",
    "        }"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example Use Case: Marketing Variation Generation\n",
    "\n",
    "Now let's see the orchestrator-workers pattern in action with a practical example: generating multiple styles of marketing copy for a product.\n",
    "\n",
    "**Why this example demonstrates the pattern well:**\n",
    "- Different products benefit from different marketing angles\n",
    "- The \"best\" variations depend on the specific product features and target audience\n",
    "- The orchestrator can adapt its strategy based on the input rather than using a fixed template\n",
    "\n",
    "**Prompt design notes:**\n",
    "- The orchestrator prompt asks for 2-3 approaches and provides XML structure guidance\n",
    "- The worker prompt gives workers full context (original task, their style, and guidelines)\n",
    "- Both prompts use clear XML formatting to ensure reliable parsing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "================================================================================\n",
      "ORCHESTRATOR ANALYSIS\n",
      "================================================================================\n",
      "\n",
      "\n",
      "This task requires creating marketing copy for an eco-friendly water bottle. The core challenge is balancing product information with persuasive messaging while highlighting the environmental benefits. Different approaches would serve distinct marketing channels and audience segments:\n",
      "\n",
      "1. A **feature-focused technical approach** would appeal to detail-oriented consumers who make purchasing decisions based on specifications, materials, and measurable environmental impact. This serves e-commerce listings and comparison shopping.\n",
      "\n",
      "2. A **lifestyle-oriented emotional approach** would connect with values-driven consumers through storytelling and aspirational messaging, emphasizing how the product fits into an eco-conscious lifestyle. This serves social media and brand-building content.\n",
      "\n",
      "3. A **benefit-driven practical approach** would focus on solving everyday problems while weaving in sustainability advantages, appealing to mainstream consumers who want both functionality and environmental responsibility. This serves broad retail contexts.\n",
      "\n",
      "Each approach addresses the \"eco-friendly\" aspect differently—through data, values, or practical advantages—making them valuable for different marketing contexts.\n",
      "\n",
      "\n",
      "\n",
      "================================================================================\n",
      "IDENTIFIED 3 APPROACHES\n",
      "================================================================================\n",
      "\n",
      "1. TECHNICAL-SPECIFICATIONS\n",
      "   >Write a detailed, feature-focused description emphasizing materials, construction, environmental certifications, and measurable sustainability metrics (recyclability percentages, carbon footprint reduction, etc.)<\n",
      "\n",
      "2. LIFESTYLE-EMOTIONAL\n",
      "   >Write an inspirational, story-driven description that connects the product to environmental values, personal identity, and the broader movement toward sustainable living<\n",
      "\n",
      "3. BENEFIT-PRACTICAL\n",
      "   >Write a problem-solution focused description highlighting everyday usability benefits (temperature retention, durability, convenience) while naturally integrating eco-friendly advantages<\n",
      "\n",
      "================================================================================\n",
      "GENERATING CONTENT\n",
      "================================================================================\n",
      "\n",
      "[1/3] Processing: technical-specifications...\n",
      "[2/3] Processing: lifestyle-emotional...\n",
      "[3/3] Processing: benefit-practical...\n",
      "\n",
      "================================================================================\n",
      "RESULTS\n",
      "================================================================================\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "Approach 1: TECHNICAL-SPECIFICATIONS\n",
      "--------------------------------------------------------------------------------\n",
      "\n",
      "\n",
      "# EcoFlow Pro™ Insulated Water Bottle - Technical Specifications\n",
      "\n",
      "## Product Overview\n",
      "Model: EF-750-INS | Capacity: 750ml (25.4 fl oz) | Weight: 285g ±5g\n",
      "\n",
      "## Material Composition & Construction\n",
      "\n",
      "### Primary Body\n",
      "- **Material**: 18/8 (304) food-grade stainless steel\n",
      "- **Wall Thickness**: 0.6mm inner wall, 0.5mm outer wall\n",
      "- **Surface Treatment**: Powder-coated finish using water-based, VOC-free coating\n",
      "- **BPA/BPS/Phthalate Status**: Certified free of all endocrine-disrupting compounds\n",
      "\n",
      "### Insulation System\n",
      "- **Technology**: Double-wall vacuum insulation with copper lining\n",
      "- **Vacuum Pressure**: <0.001 Pa\n",
      "- **Thermal Performance**: \n",
      "  - Cold retention: 24 hours (maintains <10°C)\n",
      "  - Hot retention: 12 hours (maintains >65°C)\n",
      "- **Condensation**: Zero external condensation at all temperatures\n",
      "\n",
      "### Cap & Seal Assembly\n",
      "- **Cap Material**: 100% post-consumer recycled polypropylene (rPP)\n",
      "- **Seal Gasket**: Medical-grade silicone (FDA 21 CFR 177.2600 compliant)\n",
      "- **Thread Design**: 3.5-turn precision threading for leak-proof seal (tested to 50 PSI)\n",
      "\n",
      "## Environmental Certifications & Standards\n",
      "\n",
      "- **ISO 14001**: Environmental Management System certified manufacturing facility\n",
      "- **Cradle to Cradle Certified®**: Silver level\n",
      "- **Carbon Neutral Certified**: Through verified offset programs (Climate Neutral Certified)\n",
      "- **NSF/ANSI 61**: Drinking water system components certification\n",
      "- **REACH Compliant**: European chemical safety regulation adherent\n",
      "\n",
      "## Sustainability Metrics\n",
      "\n",
      "### Carbon Footprint\n",
      "- **Manufacturing Emissions**: 2.8 kg CO₂e per unit (68% reduction vs. industry average of 8.7 kg CO₂e)\n",
      "- **Transportation Impact**: Optimized packaging reduces shipping emissions by 42%\n",
      "- **Lifecycle Offset**: Replaces approximately 217 single-use plastic bottles annually (based on average daily consumption)\n",
      "- **Net Carbon Savings**: 156 kg CO₂e per year of use vs. disposable bottle equivalent\n",
      "\n",
      "### Recyclability & Circularity\n",
      "- **End-of-Life Recyclability**: 95% by weight\n",
      "- **Stainless Steel**: 100% infinitely recyclable without quality degradation\n",
      "- **Plastic Components**: 89% recyclable (rPP cap and silicone gasket)\n",
      "- **Disassembly Time**: <45 seconds for complete material separation\n",
      "- **Take-Back Program**: Available for responsible recycling through manufacturer\n",
      "\n",
      "### Resource Efficiency\n",
      "- **Recycled Content**: 73% post-consumer recycled materials by weight\n",
      "- **Water Usage in Production**: 4.2L per unit (industry average: 12.8L)\n",
      "- **Energy Consumption**: 18.5 MJ per unit manufactured using 100% renewable energy\n",
      "- **Packaging**: 100% recycled cardboard, soy-based inks, zero plastic components\n",
      "\n",
      "## Durability & Longevity Specifications\n",
      "\n",
      "- **Impact Resistance**: Survives 2-meter drop test onto concrete (maintains vacuum seal)\n",
      "- **Corrosion Resistance**: 1,000+ hour salt spray test (ASTM B117)\n",
      "- **Cycle Testing**: 10,000+ open/close cycles without seal degradation\n",
      "- **Warranty Period**: Lifetime warranty against manufacturing defects\n",
      "- **Expected Lifespan**: 15+ years under normal use conditions\n",
      "\n",
      "## Physical Specifications\n",
      "\n",
      "- **Dimensions**: Height: 265mm | Diameter: 73mm (body), 48mm (cap)\n",
      "- **Mouth Opening**: 42mm wide-mouth design (ice cube compatible)\n",
      "- **Base Diameter**: 68mm (fits standard cup holders)\n",
      "- **Volume Markings**: Laser-etched ml/oz graduations (50ml increments)\n",
      "- **Color Options**: 8 powder-coated finishes (all VOC-free)\n",
      "\n",
      "## Compliance & Safety Testing\n",
      "\n",
      "- **FDA Approved**: All food-contact materials\n",
      "- **LFGB Certified**: German food safety standards\n",
      "- **Proposition 65**: Compliant (no listed chemicals)\n",
      "- **Lead Content**: <0.01 ppm (non-detectable)\n",
      "- **Microplastic Shedding**: Zero detected in 90-day leaching study\n",
      "\n",
      "## Performance Advantages\n",
      "\n",
      "- **Single-Use Bottle Replacement Rate**: 1:217 annually\n",
      "- **Cost Recovery Period**: 2.3 months (vs. purchasing disposable bottles)\n",
      "- **Plastic Waste Prevention**: 1.89 kg per year per user\n",
      "- **Water Quality Preservation**: No taste transfer, maintains pH neutrality (±0.1)\n",
      "\n",
      "## Manufacturing & Supply Chain\n",
      "\n",
      "- **Production Facility**: Solar-powered, zero-waste-to-landfill certified plant\n",
      "- **Supply Chain Transparency**: Full material traceability via blockchain verification\n",
      "- **Fair Trade Certified**: Ethical labor practices throughout supply chain\n",
      "- **Local Sourcing**: 67% of materials sourced within 500km of manufacturing facility\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "Approach 2: LIFESTYLE-EMOTIONAL\n",
      "--------------------------------------------------------------------------------\n",
      "\n",
      "\n",
      "\n",
      "**More Than Hydration. A Daily Ritual of Change.**\n",
      "\n",
      "Every morning, you make a choice. Not just about what you drink, but about who you are and the world you're creating.\n",
      "\n",
      "This isn't just a water bottle—it's your companion in a quiet revolution. Crafted from 100% recycled ocean-bound plastic, each bottle tells a story of transformation: waste that once threatened our seas, now reimagined as something beautiful, functional, and enduring in your hands.\n",
      "\n",
      "Feel the smooth, cool surface against your palm. Notice its weight—substantial enough to remind you it's built to last decades, not days. This is the bottle that replaces hundreds of single-use plastics, the one that travels with you through morning commutes, mountain trails, and late-night creative sessions. It becomes part of your story, collecting scratches and memories like badges of honor.\n",
      "\n",
      "But here's what really matters: You're not alone in this. You're joining millions who understand that sustainability isn't about perfection—it's about progress. Every refill is a small act of defiance against throwaway culture. Every sip connects you to a global community choosing differently, living intentionally, proving that our daily choices ripple outward in ways we can't always see but can always feel.\n",
      "\n",
      "Your hydration. Your values. Your legacy.\n",
      "\n",
      "Because the future isn't something that happens to us—it's something we carry with us, one conscious choice at a time.\n",
      "\n",
      "**Welcome to the movement. Welcome home.**\n",
      "\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "Approach 3: BENEFIT-PRACTICAL\n",
      "--------------------------------------------------------------------------------\n",
      "\n",
      "\n",
      "**Stay Hydrated All Day with the EcoFlow Bottle – Built for Your Active Life**\n",
      "\n",
      "Tired of lukewarm coffee by mid-morning or water that tastes like plastic after a few months? The EcoFlow Bottle solves the everyday frustrations that come with typical water bottles while helping you make a positive environmental impact.\n",
      "\n",
      "**Keeps Drinks at the Perfect Temperature**\n",
      "Double-wall vacuum insulation maintains cold drinks icy for 24 hours and hot beverages steaming for 12 hours. Your morning coffee stays hot through your commute, and your water remains refreshingly cold during afternoon meetings or workouts.\n",
      "\n",
      "**Built to Last Through Daily Wear and Tear**\n",
      "Constructed from premium 18/8 stainless steel with a powder-coated finish, this bottle withstands drops, bumps, and the chaos of daily life. The leak-proof lid means you can toss it in your bag without worry—no more soggy papers or ruined electronics.\n",
      "\n",
      "**Designed for Real Convenience**\n",
      "The wide mouth opening fits ice cubes easily and makes cleaning simple (no hard-to-reach corners). It fits standard cup holders in your car, and the ergonomic design is comfortable to carry whether you're commuting, hiking, or running errands.\n",
      "\n",
      "**Better for Your Wallet and the Planet**\n",
      "By switching to a reusable bottle, you'll save hundreds of dollars annually on disposable bottles while eliminating plastic waste. The durable construction means you're buying one bottle that lasts for years, not replacing cheap alternatives every few months. Plus, you'll avoid the chemicals found in many plastic bottles, ensuring cleaner-tasting water every time.\n",
      "\n",
      "**Your Reliable Hydration Companion**\n",
      "The EcoFlow Bottle adapts to your lifestyle—whether you need hot tea for early mornings, cold water for the gym, or room-temperature drinks throughout the workday. It's the practical solution that makes staying hydrated effortless while naturally reducing your environmental footprint.\n",
      "\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "ORCHESTRATOR_PROMPT = \"\"\"\n",
    "Analyze this task and break it down into 2-3 distinct approaches:\n",
    "\n",
    "Task: {task}\n",
    "\n",
    "Return your response in this format:\n",
    "\n",
    "<analysis>\n",
    "Explain your understanding of the task and which variations would be valuable.\n",
    "Focus on how each approach serves different aspects of the task.\n",
    "</analysis>\n",
    "\n",
    "<tasks>\n",
    "    <task>\n",
    "    <type>formal</type>\n",
    "    <description>Write a precise, technical version that emphasizes specifications</description>\n",
    "    </task>\n",
    "    <task>\n",
    "    <type>conversational</type>\n",
    "    <description>Write an engaging, friendly version that connects with readers</description>\n",
    "    </task>\n",
    "</tasks>\n",
    "\"\"\"\n",
    "\n",
    "WORKER_PROMPT = \"\"\"\n",
    "Generate content based on:\n",
    "Task: {original_task}\n",
    "Style: {task_type}\n",
    "Guidelines: {task_description}\n",
    "\n",
    "Return your response in this format:\n",
    "\n",
    "<response>\n",
    "Your content here, maintaining the specified style and fully addressing requirements.\n",
    "</response>\n",
    "\"\"\"\n",
    "\n",
    "\n",
    "orchestrator = FlexibleOrchestrator(\n",
    "    orchestrator_prompt=ORCHESTRATOR_PROMPT,\n",
    "    worker_prompt=WORKER_PROMPT,\n",
    ")\n",
    "\n",
    "results = orchestrator.process(\n",
    "    task=\"Write a product description for a new eco-friendly water bottle\",\n",
    "    context={\n",
    "        \"target_audience\": \"environmentally conscious millennials\",\n",
    "        \"key_features\": [\"plastic-free\", \"insulated\", \"lifetime warranty\"],\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "You've now implemented an orchestrator-workers pattern that dynamically adapts its task breakdown based on the specific input. This pattern generated multiple marketing copy variations—each tailored to different audiences and contexts—without requiring you to pre-define what those variations should be.\n",
    "\n",
    "### Key Takeaways\n",
    "\n",
    "**Pattern benefits:**\n",
    "- **Adaptability**: The orchestrator determines the best approach for each unique input\n",
    "- **Flexibility**: Easy to apply to different domains by changing the prompts\n",
    "- **Structured coordination**: XML-based communication ensures reliable parsing\n",
    "- **Error resilience**: Validation catches and handles worker failures\n",
    "\n",
    "**When this pattern excels:**\n",
    "- Content generation requiring multiple perspectives (marketing, documentation, creative writing)\n",
    "- Analysis tasks benefiting from different analytical lenses\n",
    "- Problem-solving where the decomposition strategy depends on the problem\n",
    "\n",
    "### Limitations & Considerations\n",
    "\n",
    "**Cost & Latency:**\n",
    "- Requires N+1 LLM calls (1 orchestrator + N workers)\n",
    "- Sequential processing in this implementation (workers run one at a time)\n",
    "- For better performance, consider parallelizing worker calls with `asyncio` or thread pools\n",
    "\n",
    "**When NOT to use this pattern:**\n",
    "- Simple tasks with single, clear outputs (the added complexity isn't justified)\n",
    "- Latency-critical applications (multiple API calls add overhead)\n",
    "- Tasks where subtasks are always the same (use pre-defined parallelization instead)\n",
    "\n",
    "**Failure modes to consider:**\n",
    "- Orchestrator might not break down tasks optimally (prompt engineering is critical)\n",
    "- Workers may return empty or malformed responses (we handle this with validation)\n",
    "- XML parsing can fail if models don't follow format exactly (consider using JSON as an alternative)\n",
    "\n",
    "### Next Steps\n",
    "\n",
    "**Enhance this implementation:**\n",
    "1. Add parallel worker execution using `asyncio` for better performance\n",
    "2. Implement retry logic for failed workers\n",
    "3. Add a synthesis phase where an LLM combines worker outputs\n",
    "4. Experiment with different orchestrator strategies (e.g., asking for more/fewer subtasks)\n",
    "\n",
    "**Adapt to your use case:**\n",
    "- Modify the orchestrator prompt to guide task decomposition for your domain\n",
    "- Adjust worker prompts to provide domain-specific instructions\n",
    "- Add context parameters relevant to your application\n",
    "- Consider using Claude Opus for the orchestrator and Claude Haiku for workers to optimize cost vs. quality"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "anthropic-cookbook (3.12.12)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}